<template>
  <el-dialog class="dialog" :model-value="visible" :show-close="false" width="40%" :z-index="9" top="5vh">
    <div class="boardBox">
   
      <!-- 扫描进度条 -->
      <div class="progress-container" v-if="loading">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${currentProgress}%` }"></div>
        </div>
        <div class="progress-text">{{ currentProgress }}%</div>
      </div>
      <div class="formBoxcont">
        <div class="font20 color333 mb10 ml20">企业人力资源合规风险扫描仪</div>
        <div class="formBoxtou flex flex-align-center mt20">
          <div><img src="@/assets/image/cf/img26.png" alt="" /></div>
          <div class="flex flex-align-center flex-1">
            <div class="flex box-row-column ml20">
              <div class="font18 color333" v-if="loading">
                共发现
                <span class="colorff1200">{{ totalRiskCount }}</span>
                个风险点
              </div>

              <div class="font18 color333" v-else>
                扫描完成！ 共发现
                <span class="colorff1200">{{ totalRiskCount }}</span>
                个风险点，合规值为
                <span :class="totalScore > 70 ? colorff1200 : color2de07b">{{ totalScore }}</span>
                分
              </div>
              <div class="flex mt10 fxzi1" style="" v-if="!loading">
                <el-icon color="#01509f" style="margin-top: 2px"><Warning /></el-icon>
                系统将于每月月初进行合规风险自动扫描
              </div>

              <div class="flex mt10 fxzi1" style="" v-if="totalScore > 0">
                <el-icon color="#01509f" style="margin-top: 2px"><Warning /></el-icon>

                {{ totalScore > 70 ? "请注意合规风险" : "当前企业合规情况较差，存在较多合规风险，需立即整改，避免法律风险。" }}
              </div>
            </div>
          </div>

          <div class="tou_close"  v-if="loading">扫描中...</div>
              <div class="tou_close" @click="cancel" v-else>关 闭</div>
        </div>

        <div class="flex box-row-column mt20" style="padding: 0px 30px">
          <div class="flex box-row-column" v-for="(modules, type) in categories" :key="type">
            <div class="lizhi">{{ type }}</div>
            <div class="flex-container mt20">
              <div class="flex-item" v-for="module in modules" :key="module.id">
                <div><img :src="module.img" alt="" /></div>
                <div class="item-title">{{ module.name }}</div>
                <div class="item-wufenxian" v-if="!module.loaded">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                </div>
                <div class="item-wufenxian" v-if="module.count == 0">
                  <img src="@/assets/image/cf/imgdui.png" alt="" />
                  未扫出风险
                </div>

                <div class="item-saomiao" v-else>风险点:{{ module.count }}</div>
              </div>
              <!-- <div class="flex-item" >
                <div><img src="@/assets/image/cf/lizhixinzi.png" alt="" /></div>
                <div class="item-title">离职工资发放</div>

                <div class="item-saomiao">扫描中</div>
              </div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, ref, computed } from 'vue';
import { Loading } from '@element-plus/icons-vue';
import { useCompanyDataStore } from '@/store/companys';

interface RiskModule {
  id: number;
  type: string;
  name: string;
  img: string;
  x_img: string;
  count: number;
  progress: number;
  loaded: boolean; // 新增字段，标记是否已加载完成
}


export default defineComponent({
  name: 'RiskScanner',
  components: { Loading },
  setup() {
    const loading = ref(true);
    const currentProgress = ref(0);
    const currentScanningModule = ref('');
    const categories = ref<Record<string, RiskModule[]>>({});
    const totalScore = ref(0);
    const companyDataStore = useCompanyDataStore();

    // 计算总风险数
    const totalRiskCount = computed(() => {
      return Object.values(categories.value).reduce((total, modules) => {
        return total + modules.reduce((sum, module) => sum + module.count, 0);
      }, 0);
    });

    // 获取分类图标
    const getCategoryIcon = (type: string) => {
      const category = categories.value[type];
      return category && category.length > 0 ? category[0].x_img : '';
    };

    // 计算分类风险数
    const getCategoryRiskCount = (type: string) => {
      return categories.value[type]?.reduce((sum, module) => sum + module.count, 0) || 0;
    };

    // 分数标签类型
    const getScoreTagType = (score: number) => {
      return score >= 80 ? 'success' : 
             score >= 60 ? 'warning' : 'danger';
    };

    // 调用流式接口
    const loadRiskData = async () => {
      try {
        const companyId = companyDataStore.currentComanyInfo.id;
        const response = await fetch(
          `https://demo-api.niuyuwang.com/hr/detection/risk_check?company_id=${companyId}`,
          { headers: { Accept: 'text/event-stream' } }
        );

        if (!response.ok) throw new Error('接口请求失败');
        if (!response.body) throw new Error('不支持流式数据');

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const text = decoder.decode(value);
          const lines = text.split('\n').filter(line => line.trim() !== '');
          
          for (const line of lines) {
            if (line.startsWith('data:')) {
              const data = JSON.parse(line.substring(5).trim());
              
              if (data.status === 'starting') {
                categories.value = {};
                currentProgress.value = 0;
              } 
              else if (data.all_totle !== undefined) {
                // 使用 all_totle 作为总分
                totalScore.value = data.all_totle;
                loading.value = false;
              }
              else if (data.id !== undefined) {
                if (!categories.value[data.type]) {
                  categories.value[data.type] = [];
                }
                // 添加loaded字段，初始为false
                const moduleData = { ...data, loaded: false };
                categories.value[data.type].push(moduleData);
                currentProgress.value = data.progress;
                currentScanningModule.value = data.name;
                
                // 模拟延迟加载效果
                setTimeout(() => {
                  moduleData.loaded = true;
                }, 500 + Math.random() * 1000);
              }
            }
          }
        }
      } catch (err) {
        console.error('扫描失败:', err);
      }
    };

    // 初始化加载数据
    loadRiskData();

    return {
      loading,
      currentProgress,
      currentScanningModule,
      categories,
      totalScore,
      totalRiskCount,
      getCategoryIcon,
      getCategoryRiskCount,
      getScoreTagType
    };
  }
});

  // function cancel() {
  //   emit("update:visible", false);
  //   emit("chananniu", "");
  // }
</script>
<style>
.dialog {
  background-color: rgba(255, 255, 255, 0);
  /* 完全透明 */
  box-shadow: none;
  /* 移除阴影 */
}
</style>
<style lang="scss" scoped>
.boardBox {
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* 垂直居中 */

  /* 水平居中 */
  width: 100%;

  overflow: hidden;
  height: calc(100vh - 172px);

  &::-webkit-scrollbar {
    display: none;
  }

  -ms-overflow-style: none;
  scrollbar-width: none;

  .tishi {
    font-size: 14px;
    color: #999;
    background-color: #f3f8fb;
    padding: 5px 10px;
    border-radius: 6px;
  }

  .formBoxtou {
    background-color: #f3f9ff;

    padding: 20px 50px;
  }

  .fxzi1 {
    color: #01509f;
    background-color: #f3f8fb;
    font-size: 12px;
    border-radius: 5px;
    padding: 5px;
  }

  .tou_close {
    font-size: 15px;
    color: #01509f;
    border: solid 1px #01509f;
    border-radius: 50px;
    text-align: center;
    line-height: 30px;
    width: 70px;
  }

  .formBoxcont {
    padding: 20px 0px;
    background-color: #fff;

    border-radius: 10px;

    height: 100%;
    overflow: auto;
    margin-top: 30px;
    display: flex;
    flex-direction: column;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .fxzi2 {
    font-size: 15px;
    color: #666;
  }

  .lizhi {
    font-size: 17px;
    color: #333;
    font-weight: 500;
    // background: url("@/assets/image/cf/imglz.png") no-repeat left center;
    // background-size: 20px 20px;
    // padding-left: 25px;
  }

  .flex-container {
    display: flex;
    flex-wrap: wrap;
    /* 超出换行 */
    justify-content: flex-start;
    /* 左对齐 */
    gap: 10px;
    /* 子项间距 */
  }

  .flex-item {
    width: 20%;
    /* 固定宽度 */

    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    margin-bottom: 10px;
  }

  .item-title {
    margin-top: 8px;
    margin-bottom: 8px;
    font-size: 15px;
    color: #333;
  }

  .item-wufenxian {
    padding: 0px 10px;
    line-height: 25px;
    background-color: #dbffeb;
    text-align: center;
    border: solid 1px #1fbe7d;
    color: #1fbe7d;
    border-radius: 50px;
  }

  .item-saomiao {
    padding: 0px 20px;
    line-height: 25px;
    background-color: #fff4f4;
    text-align: center;
    border: solid 1px #ffb8b8;
    color: #666;
    border-radius: 50px;
  }

  .scan-status {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #01509f;
    font-size: 14px;
  }

  .progress-container {
    margin: 30px 0;
    text-align: center;
  }

  .progress-bar {
    height: 10px;
    background: #f0f0f0;
    border-radius: 5px;
    overflow: hidden;
    margin-bottom: 10px;
  }

  .progress-fill {
    height: 100%;
    background: #01509f;
    transition: width 0.3s ease;
  }

  .progress-text {
    font-size: 14px;
    color: #666;
  }

  .categories-container {
    margin-top: 20px;
  }
}

::v-deep .el-form-item__label {
  font-size: 16px !important;
}
</style>
